// 知识点详情页面交互功能
document.addEventListener('DOMContentLoaded', function() {
    // 初始化掌握度圆形图
    initMasteryCircle();

    // 初始化进度条动画
    initProgressBars();

    // 绑定关联知识点点击事件
    bindRelatedKnowledgeEvents();

    // 初始化练习记录筛选
    initPracticeFilter();

    // 绑定学习建议交互
    bindSuggestionEvents();

    // 初始化边际收益指示器
    renderMarginalGain();

    // 更新练习统计
    updatePracticeStats();
});

// 获取掌握度等级
function getMasteryLevel(percent) {
    if (percent >= 80) return 'excellent';
    if (percent >= 60) return 'good';
    if (percent >= 40) return 'average';
    return 'poor';
}

// 获取掌握度颜色
function getMasteryColor(level) {
    const colors = {
        excellent: '#28a745',
        good: '#17a2b8',
        average: '#ffc107',
        poor: '#dc3545'
    };
    return colors[level] || '#6c757d';
}

// 初始化掌握度圆形图
function initMasteryCircle() {
    const masteryCircle = document.querySelector('.mastery-circle');
    if (!masteryCircle) return;

    const masteryPercent = parseFloat(masteryCircle.dataset.mastery);
    const masteryLevel = getMasteryLevel(masteryPercent * 100);
    const masteryColor = getMasteryColor(masteryLevel);

    const progressCircle = masteryCircle.querySelector('.mastery-progress');
    const circumference = 2 * Math.PI * 54; // 半径54

    // 设置颜色
    progressCircle.style.stroke = masteryColor;

    // 计算进度
    const offset = circumference - (masteryPercent * circumference);

    // 延迟执行动画
    setTimeout(() => {
        progressCircle.style.strokeDashoffset = offset;
    }, 300);

    // 添加旋转动画效果
    setTimeout(() => {
        masteryCircle.style.animation = 'rotate 2s ease-out';
    }, 500);
}

// 初始化进度条动画
function initProgressBars() {
    const progressBars = document.querySelectorAll('.progress-bar');
    progressBars.forEach(bar => {
        const width = bar.style.width;
        bar.style.width = '0';
        setTimeout(() => {
            bar.style.width = width;
        }, 300);
    });
}

// 绑定关联知识点点击事件
function bindRelatedKnowledgeEvents() {
    const relatedItems = document.querySelectorAll('.related-item');
    relatedItems.forEach(item => {
        item.addEventListener('click', function() {
            const knowledgeId = this.dataset.knowledgeId;
            if (knowledgeId) {
                window.location.href = `/analysis/knowledge-point/${knowledgeId}/`;
            }
        });

        // 悬停效果
        item.addEventListener('mouseenter', function() {
            this.style.transform = 'translateX(5px)';
        });

        item.addEventListener('mouseleave', function() {
            this.style.transform = 'translateX(0)';
        });
    });
}

// 初始化练习记录筛选
function initPracticeFilter() {
    const filterButtons = document.querySelectorAll('.practice-filter');
    const practiceRows = document.querySelectorAll('.practice-row');

    filterButtons.forEach(button => {
        button.addEventListener('click', function() {
            const filter = this.dataset.filter;

            // 更新按钮状态
            filterButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');

            // 筛选练习记录
            practiceRows.forEach(row => {
                if (filter === 'all' || row.dataset.result === filter) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        });
    });
}

// 绑定学习建议交互
function bindSuggestionEvents() {
    const suggestionItems = document.querySelectorAll('.suggestion-item');

    suggestionItems.forEach(item => {
        // 初始设置描述文本高度
        const content = item.querySelector('.suggestion-desc');
        content.style.maxHeight = '3em';

        item.addEventListener('click', function() {
            this.classList.toggle('expanded');

            if (this.classList.contains('expanded')) {
                content.style.maxHeight = content.scrollHeight + 'px';
            } else {
                content.style.maxHeight = '3em';
            }
        });
    });
}

// 边际收益可视化
function renderMarginalGain() {
    const gainBar = document.querySelector('.gain-bar');
    if (!gainBar) return;

    const gainValue = parseFloat(gainBar.dataset.gain);
    const normalizedGain = Math.min(Math.max(gainValue * 100, 0), 100);

    // 设置颜色基于收益值
    let gainColor;
    if (gainValue > 0.7) gainColor = '#28a745';
    else if (gainValue > 0.4) gainColor = '#ffc107';
    else gainColor = '#dc3545';

    // 延迟执行动画
    setTimeout(() => {
        gainBar.style.width = normalizedGain + '%';
        gainBar.style.background = gainColor;
    }, 500);
}

// 练习记录统计
function updatePracticeStats() {
    const totalPractices = document.querySelectorAll('.practice-row').length;
    const correctPractices = document.querySelectorAll('.practice-row[data-result="correct"]').length;
    const accuracy = totalPractices > 0 ? (correctPractices / totalPractices * 100).toFixed(1) : 0;

    // 更新统计显示
    const accuracyElement = document.getElementById('practice-accuracy');
    if (accuracyElement) {
        accuracyElement.textContent = accuracy + '%';
    }
}

// 导出功能
function exportKnowledgeData() {
    const knowledgeName = document.querySelector('.knowledge-header h1').textContent;
    const masteryPercent = document.querySelector('.mastery-circle span').textContent;

    const knowledgeData = {
        name: knowledgeName,
        mastery: masteryPercent,
        stats: {
            totalPractices: document.querySelectorAll('.practice-row').length,
            accuracy: document.getElementById('practice-accuracy')?.textContent,
            marginalGain: document.querySelector('.gain-value')?.textContent
        },
        exportTime: new Date().toISOString()
    };

    const dataStr = JSON.stringify(knowledgeData, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});

    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `knowledge-${knowledgeName.replace(/\s+/g, '-')}-data.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    URL.revokeObjectURL(url);

    // 显示导出成功提示
    showNotification('数据导出成功！', 'success');
}

// 显示通知
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show`;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 300px;
    `;
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(notification);

    // 自动移除通知
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}

// 添加到全局作用域
window.exportKnowledgeData = exportKnowledgeData;

// 页面离开前提示
window.addEventListener('beforeunload', function() {
    // 可以添加保存进度等逻辑
});